package com.luke.auth_server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.Arrays;

/**
 * TODO 代码可以优化
 * 配置授权服务
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Bean
    public ClientDetailsService clientDetailsService(DataSource dataSource) {
        ClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        ((JdbcClientDetailsService) clientDetailsService).setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
    }

    //1、配置客户端详情服务（平台对哪些客户端开放认证授权）
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        /*clients.inMemory()
                .withClient("c1")//客户端ID，即client_id
                .secret(new BCryptPasswordEncoder().encode("secret"))//客户端密钥，即secret
                .resourceIds("res1")//客户端可以访问的资源列表（通常一个资源ID就代表一个资源服务，即微服务）
                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")//授权类型
                .scopes("all")//允许客户端的授权范围（表示一个自定义的标识）
                .autoApprove(false) // false：跳转到授权页面
                .redirectUris("http://www.baidu.com");//加上验证回调地址*/

        clients.withClientDetails(clientDetailsService);
    }

    //-------------------------------------------------------令牌管理服务-----------------------------------------------------------

    @Autowired
    private TokenStore tokenStore;


    @Autowired
    private JwtAccessTokenConverter accessTokenConverter;

    //2、令牌管理服务
    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices services = new DefaultTokenServices();
        services.setClientDetailsService(clientDetailsService);//客户端详情
        services.setSupportRefreshToken(true);//支持刷新
        services.setTokenStore(tokenStore);//令牌存储策略

        //增强Token
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        services.setTokenEnhancer(tokenEnhancerChain);

        services.setAccessTokenValiditySeconds(7200);//令牌有效期2小时
        services.setRefreshTokenValiditySeconds(359200);//刷新令牌有效期3天
        return services;
    }

    //------------------------------------------------------令牌的访问端点------------------------------------------------------------

    //授权码如何存储
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) {
        //return new InMemoryAuthorizationCodeServices(); //内存模式
        return new JdbcAuthorizationCodeServices(dataSource);//数据存储授权码
    }

    @Autowired
    private AuthenticationManager authenticationManager;//用于密码模式

    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;//用于授权码模式

    //3、令牌的访问端点
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)//密码模式需要：认证管理器
                .authorizationCodeServices(authorizationCodeServices)//授权码模式需要：授权码服务
                .tokenServices(tokenServices())//令牌管理服务
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);//令牌端点请求类型
    }

    //------------------------------------------------------令牌访问端点安全约束------------------------------------------------------------

    //4、令牌访问安全策略
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")//oauth/token_key JWE公钥公开
                .checkTokenAccess("permitAll()") //oauth/check_token公开
                .allowFormAuthenticationForClients(); //表单认证（申请令牌）
    }
}
